package 优先算法.递归_搜索与回溯.二叉树深度搜索.二叉树剪枝;

/**
 *https://leetcode.cn/problems/binary-tree-pruning/
 */
public class Main {
    public static void main(String[] args) {
        Solution so = new Solution();
        Solution.TreeNode root = new Solution.TreeNode(1);
        root.left = new Solution.TreeNode(1);
        root.right = new Solution.TreeNode(0);
        root.left.left = new Solution.TreeNode(0);
        root.left.right = new Solution.TreeNode(1);

        Solution.TreeNode rel = so.pruneTree(root);
        printTree(rel); // 打印剪枝后的树
    }
    private static void printTree(Solution.TreeNode node) {
        if (node == null) return;
        System.out.print(node.val + " ");
        printTree(node.left);
        printTree(node.right);
    }
}
class Solution {
    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public TreeNode pruneTree(TreeNode root) {
        if (root == null) {
            return null;
        }
        root.left = pruneTree(root.left);
        root.right = pruneTree(root.right);
        if (root.val == 0 && root.left == null && root.right == null) {
            return null;
        }
        return root;
    }
}
